//BufferBuilderTest.java
package com.ylaihui.stringbufferbuilder;

import org.junit.Test;

public class BufferBuilderTest {
    @Test
    public void test1(){
        String s1 = new String();  // this.value = "".value;

        String s2 = new String("ylaihui");  // 底层有两个对象， 一个是 new的对象，一个是 original 对象
        String s3 = "ylaihui";
        System.out.println(s2 == s3);  // false

        // StringBuffer 继承了 AbstractStringBuilder
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer("ylaihui"); // char[] value = new char[16];底层创建了一个长度是16的字符数组。

        System.out.println(sb1.length()); // 0
        System.out.println(s2.length()); // 7

        StringBuilder sbd1 = new StringBuilder();
        // 与 StringBuffer 相同， StringBuilder 也继承了 AbstractStringBuilder
        StringBuilder sbd2 = new StringBuilder("ylaihui");
    }

    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("ylaihui");
        s1.append(1);
        s1.append('1');
        System.out.println(s1);
//        s1.delete(2,4);
//        s1.replace(2,4,"hello");
//        s1.insert(2,false);
//        s1.reverse();
        String s2 = s1.substring(1, 3);
        System.out.println(s1);
        System.out.println(s1.length());
        System.out.println(s2);
    }

    @Test
    public void test3(){
            //初始设置
            long startTime = 0L;
            long endTime = 0L;
            String text = "";
            StringBuffer buffer = new StringBuffer("");
            StringBuilder builder = new StringBuilder("");
            //开始对比
            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                buffer.append(String.valueOf(i));
            }
            endTime = System.currentTimeMillis();
            System.out.println("StringBuffer的执行时间：" + (endTime - startTime));

            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                builder.append(String.valueOf(i));
            }
            endTime = System.currentTimeMillis();
            System.out.println("StringBuilder的执行时间：" + (endTime - startTime));

            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                text = text + i;
            }
            endTime = System.currentTimeMillis();
            System.out.println("String的执行时间：" + (endTime - startTime));
    }
}
